<?php

/**
 * Created by lunzi.
 * User: lunzi
 * Date: 15-6-03
 * Time: 下午2:54
 */

class WX_Controller extends CI_Controller
{

    protected $user = array(); //当前操作的商户
    protected $admin = array();
    protected $current_time = '';
    protected $open_id = null;
    protected $serverphone = "400-882-7781"; //客服电话
    protected $data = array('site_title' => '财神位');


    public function __construct()
    {
        parent::__construct();
        $this->current_time = time();


        //$this->_init_visitor(); //正式初始化访问者
        //$this->temp_init_visitor(); //临时初始化访问者
        $this->_init__no_visitor(); //无需获取微信信息，适用于登录

    }
    //无需获取用户授权的访问数据
    protected function _init__no_visitor()
    {
        $this->load->library('wx_visitor');
        $request_url = explode('?', $_SERVER['REQUEST_URI']);
        $this->user = $this->wx_visitor->get_info();

        if (!$this->user) {
            if ($this->input->is_ajax_request()) {
                exit(getJsonOutput(array('status' => false, 'data' => '请先登录！')));
            } else {
                redirect('http://' . $_SERVER['HTTP_HOST'] . '/wap/login');
            }
        }
    }
    //临时初始化访问者数据方法
    protected function temp_init_visitor()
    {
        $this->user['id'] = '11';
        $this->user['username'] = '王洁';
        $this->user['phone'] = '13603092536';
        $this->user['open_id'] = 'owRuZuJ-F3vLO8BqvuXzYjsQzeOs';
        $this->user['user_nick'] = 'Allen';
        $this->user['avatar'] = 'http://wx.qlogo.cn/mmopen/ajNVdqHZLLC6l9QAMFW0sdCpYWNy96M0s37XicdHL1AkQOoQ2v8KTqmSe1cajT1zQsJXushzcLRIFYjTnUSAib0w/0'; //头像
    }

    //临时初始化访问者数据方法
    //     protected function temp_init_visitor()
    //     {
    //     	$this->user['id'] = '14';
    //     	$this->user['username'] = '郭梦丹';
    //     	$this->user['phone'] = '15270994343';
    //     	$this->user['open_id'] = 'owRuZuJ-F3vLO8BqvuXzYjsQzeOs';
    //     	$this->user['user_nick'] = '不多不少啦C梦';
    //     	$this->user['avatar'] = 'http://wx.qlogo.cn/mmopen/sSLibS6pF8ib7JNIZS75SGOdPZHSPyJm2rvwC7ia7fjx7VzUDYuDgVkpYQKzhZu8WmgHxibz6AnzLGYOsO9E1rIkXJO7jhe2ItYJ/0';//头像
    //     }

    protected function _init_visitor()
    {
        $this->load->library('wx_visitor');
        $request_url = explode('?', $_SERVER['REQUEST_URI']);

        $this->user = $this->wx_visitor->get_info();
        if (!$this->user) {
            $this->wx_visitor->signout();
            redirect('http://' . $_SERVER['HTTP_HOST'] . '/wap/oauth?url=' . $request_url['0']);
        }
        $this->user = $this->wx_visitor->get_info();
    }


    public function response($array = array(), $http_code = 200)
    {
        $CI = &get_instance();
        $callback = $CI->input->get('callback');

        header('HTTP/1.1: ' . $http_code);
        header('Status: ' . $http_code);

        if ($callback) {
            header('Content-type: application/javascript');
            exit($callback . '(' . json_encode($array) . ');');
        } else {
            header('Content-type: application/json');
            exit(json_encode($array));
        }
    }

    //设置
    public function assign($name, $value)
    {
        $this->data[$name] = $value;
    }
    //view
    public function display($file)
    {

        $this->load->view($file, $this->data);
    }


    /**
     * 上传图片
     * create by chenqi
     */
    function uploadPic($img, $type)
    {
        switch ($type) {
            case 'image/png':
                $ext = '.png';
                break;
            case 'image/jpeg';
                $ext = '.jpeg';
                break;
            case 'image/jpeg':
                $ext = '.jpg';
                break;
            case 'image/bmp':
                $ext = '.bmp';
                break;
            default:
                $ext = '.jpg';
        }
        $r = rand(10, 1000);
        $file_path = $this->config->item('upload_wap_path') . '/' . time() . '_' . $r . $ext;
        $img_content = str_replace('data:' . $type . ';base64,', '', $img);
        $img_content = base64_decode($img_content);
        $res = file_put_contents($file_path, $img_content);
        if ($res) {
            return "/" . $file_path;
        }
        return $res;
    }


    //跳转
    public function location_href($text, $go_url)
    {
        echo "<script>alert('$text');window.location.replace('$go_url');</script>";
        exit;
    }
    /**
     * 添加收入记录
     */
    public function add_money_log($data = array())
    {
        if ($data) {
            $this->load->model('money_log_model');
            foreach ($data as $key => $value) {
                $this->money_log_model->addMoneyLog($value);
            }
        }
        return true;
    }
    //拼接地区
    public function get_post($data, $field)
    {
        $province = $data['province'];
        $city = $data['city'];
        $county = $data['county'];
        $province = explode(",", $province);
        $city = explode(",", $city);
        $county = explode(",", $county);
        $areas['area_no'] = $province[0] . ',' . $city[0] . ',' . $county[0];
        $areas['detail'] = $province[1] . $city[1] . $county[1];
        $data[$field] = serialize($areas);
        unset($data['province']);
        unset($data['city']);
        unset($data['county']);
        return $data;
    }

    /**
     * 用户资金更换，后续操作
     * @param type $user
     * @param type $parent_user
     */
    public function zhitui($user = array(), $parent_user = array())
    {
        $this->load->model('user_model');
        if ($user['parent_id'] > 0) {
            $where = array('id' => $user['parent_id']);
            $shouru = $user['price'] * 0.3;
            //$performance=$user['price']+$parent_user['performance'];
            $next_count = $parent_user['next_count'] + 1;
            $update = array('money' => $parent_user['money'] + $shouru, 'balance' => $parent_user['balance'] + $shouru, 'next_count' => $next_count);
            $result = $this->user_model->editUser($where, $update);
            if ($result) {
                $this->load->model('user_level_model');
                $level_info = $this->user_level_model->checkUserLevel(array('id' => $parent_user['user_level']));
                $data[] = array(
                    'user_id' => $parent_user['id'],
                    'username' => $parent_user['username'],
                    'true_name' => $parent_user['true_name'],
                    'money' => $shouru,
                    'type' => 'direct',
                    'remark' => '您的下级' . $user['true_name'] . '给你带来' . $shouru . '收入,',
                    'type_name' => '直推',
                    'user_level_name' => $level_info['user_level_name'],
                    'from_user_id' => $user['id'],
                    'from_user_name' => $user['username'],
                    'create_time' =>  time()
                );

                $this->add_money_log($data);
            } else {
                return false;
            }
        }
        return true;
    }
    /**
     * 
     * @return boolean直推奖2
     */
    public function zhitui2($user = array(), $parent_user = array())
    {

        $this->load->model('user_model');
        if ($user['parent_id'] > 0) {
            $this->load->model('user_level_model');
            $level_info = $this->user_level_model->checkUserLevel(array('id' => $parent_user['user_level']));
            $parent_user['user_level_name'] = $level_info['user_level_name'];
            $parent_user['use_level_id'] = $level_info['use_id'];
            $where = array('id' => $user['parent_id']);
            $lv = $level_info['zhitui'];
            /*switch ($parent_user['use_level_id']) {
                     case '1':
                         $lv=0.3;
                         break;
                     case '2':
                         $lv=0.38;
                         break;
                     case '3':
                         $lv=0.43;
                         break;
                     default:
                         break;
                 }*/
            $shouru = $user['price'] * $lv;

            //$performance=$user['price']+$parent_user['performance'];
            $next_count = $parent_user['next_count'] + 1;
            $update = array('money' => $parent_user['money'] + $shouru, 'balance' => $parent_user['balance'] + $shouru, 'next_count' => $next_count);
            $result = $this->user_model->editUser($where, $update);

            if ($result) {
                $data[] = array(
                    'user_id' => $parent_user['id'],
                    'username' => $parent_user['username'],
                    'true_name' => $parent_user['true_name'],
                    'money' => $shouru,
                    'type' => 'direct',
                    'remark' => '您的下级' . $user['true_name'] . '给你带来' . $shouru . '收入,',
                    'type_name' => '直推',
                    'user_level_name' => $parent_user['user_level_name'],
                    'from_user_id' => $user['id'],
                    'from_user_name' => $user['username'],
                    'create_time' =>  time()
                );

                $this->add_money_log($data);
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 三级收入（平级奖）
     * @pqram type $user 当前审核的用户
     * @param type $parent_user 父级用户
     * @param type $parent_parent_user 父级父级用户
     * @return bool
     */
    public function distribution($user = array(), $parent_user = array(), $parent_parent_user = array())
    {
        if ($parent_parent_user && $parent_user['parent_id'] == $parent_parent_user['id']) {
            $next_next_count = $parent_parent_user['next_next_count'] + 1;
            // $performance=$parent_parent_user['performance']+$user['price']; //此处业绩在下面计算
            $update = array();
            $where = array();
            $where['id'] = $parent_parent_user['id'];
            //$update['performance']=$performance;
            $update['next_next_count'] = $next_next_count;
            $money_range = 0;
            $money = 0;
            $distribution = 'range';
            $distribution_desc = '极差';
            $this->load->model('user_level_model');
            $money_range = $this->user_level_model->level_rang($parent_parent_user['user_level'], $parent_user['user_level']);

            if ($parent_parent_user['user_level'] == $parent_user['user_level']) {
                $distribution = 'concur';
                $distribution_desc = '互助';
            }
            if ($money_range != 0) {
                $this->load->model('user_model');
                $money = $user['price'] * $money_range;
                $update['money'] = $parent_parent_user['money'] + $money;
                $update['balance'] = $parent_parent_user['balance'] + $money;
            }
            $result = $this->user_model->editUser($where, $update);
            if ($result && $money > 0) {
                $data[] = array(
                    'user_id' => $parent_parent_user['id'],
                    'username' => $parent_parent_user['username'],
                    'true_name' => $parent_parent_user['true_name'],
                    'money' => $money,
                    'type' => $distribution,
                    'remark' => '您的下级' . $user['true_name'] . '，给你带来' . $money . $distribution_desc . '收入,',
                    'create_time' =>  time()
                );
                $this->add_money_log($data);
            }
        }
        return true;
    }
    /**
     * 新增会员如果有父级处理
     */
    public function shouru($user, $parent_user, $parent_parent_user, $levels = 1, $is_ping = true, $end_level = 4, $is_start = true)
    {

        $this->load->model('user_model');
        $this->load->model('user_level_model');
        if (!isset($user['use_level_id'])) {
            $user_level = $this->user_level_model->checkUserLevel(array('id' => $user['user_level']));
            $user['use_level_id'] = $user_level['use_id'];
            $user['user_level_name'] = $user_level['user_level_name'];
        }
        if (!isset($parent_user['use_level_id'])) {
            $user_level = $this->user_level_model->checkUserLevel(array('id' => $parent_user['user_level']));
            $parent_user['use_level_id'] = $user_level['use_id'];
            $parent_user['user_level_name'] = $user_level['user_level_name'];
        }
        if (!isset($parent_parent_user['use_level_id'])) {
            $user_level = $this->user_level_model->checkUserLevel(array('id' => $parent_parent_user['user_level']));
            $parent_parent_user['use_level_id'] = $user_level['use_id'];
            $parent_parent_user['user_level_name'] = $user_level['user_level_name'];
        }

        if ($parent_parent_user && $is_start) {
            if (($parent_parent_user['use_level_id'] >= $parent_user['use_level_id']) && ($parent_parent_user['use_level_id'] >= $levels)) {

                $update = array();
                $where = array();
                $where['id'] = $parent_parent_user['id'];
                $money_range = 0;
                $money = 0;

                //                    if($parent_parent_user['user_level']==$end_level && $is_ping){
                //                        $distribution='concur';
                //                        $distribution_desc='互助';
                //                        $money_range=0.02;
                //						$is_ping=false;
                //                    }else
                if ($parent_parent_user['use_level_id'] == $levels && $is_ping) {
                    $distribution = 'concur';
                    $distribution_desc = '互助';
                    $money_range = 0.02;
                    $is_ping = false;
                    //$levels++;


                } else if ($parent_parent_user['use_level_id'] > $levels) {
                    $distribution = 'range';
                    $distribution_desc = '极差';
                    $this->load->model('user_level_model');

                    $money_range = $this->user_level_model->level_rang($parent_parent_user['use_level_id'], $levels);

                    $is_ping = true;
                }
                //判断获得佣金比率是否大于0
                if ($money_range > 0) {
                    $levels = $parent_parent_user['use_level_id'];
                    $this->load->model('user_model');
                    $money = $user['price'] * $money_range;
                    $update['money'] = $parent_parent_user['money'] + $money;
                    $update['balance'] = $parent_parent_user['balance'] + $money;
                    $result = $this->user_model->editUser($where, $update);
                    if ($result && $money > 0) {
                        $data[] = array(
                            'user_id' => $parent_parent_user['id'],
                            'username' => $parent_parent_user['username'],
                            'true_name' => $parent_parent_user['true_name'],
                            'money' => $money,
                            'type' => $distribution,
                            'type_name' => $distribution_desc,
                            'remark' => '您的下级' . $user['true_name'] . '，给你带来' . $money . $distribution_desc . '收入,',
                            'create_time' =>  time(),
                            'user_level_name' => $parent_parent_user['user_level_name'],
                            'from_user_id' => $user['id'],
                            'from_user_name' => $user['username'],
                        );
                        $this->add_money_log($data);
                    }
                }
            }

            if ($parent_parent_user['parent_id']) {
                $parent_parent_user2 = array();
                $parent_parent_user2 = $this->user_model->checkUser(array('user.id' => $parent_parent_user['parent_id']));



                $this->shouru($user, $parent_parent_user, $parent_parent_user2, $levels, $is_ping, $end_level, $is_start);
            }
        }
        return true;
    }

    /**
     * 会员等级更新
     */
    public function update_level()
    {
        $this->load->model('user_model');
        $group_money = $this->user_model->select('sum(price) as group_performance')->find();

        $today = date("Y-m-d");
        $day = $this->getthemonth($today);
        $firstday =  strtotime($day[0]);
        $lastday = strtotime($day[1]);
        $mouth_money_tmp = $this->user_model->where("create_time between " . $firstday . " and " . $lastday)->select('sum(price) as mouth_money')->find();
        $mouth_money = $mouth_money_tmp['mouth_money'];


        $this->load->model('user_level_model');
        $user_level_where = array();
        $user_level_where['status'] = 1;
        $user_level_where['is_default !='] = '1';
        $user_level_where['group_performance <='] = $group_money['group_performance'];
        $user_levels = $this->user_level_model->getUserLevelList($user_level_where, '100', '0', 'group_performance asc');



        foreach ($user_levels as $key => $user_level_value) {
            if ($user_level_value['group_performance'] > $group_money) {
                break;
            } else {
                $user_tmp_where = array();
                $first_money = $user_level_value['other_performance'];
                $user_tmp_where['performance >='] = $first_money;
                if (isset($user_levels[$key + 1])) {
                    $last_money = $user_levels[$key + 1]['other_performance'];
                    $user_tmp_where['performance <'] = $last_money;
                }
                $user_tmp_where['user_level !='] = $user_level_value['id'];
                $user_tmp = array();

                $user_tmp =  $this->user_model->getUserList($user_tmp_where);


                foreach ($user_tmp as $user_key => $user_value) {
                    $parent_user_where = array();
                    $parent_user_where['parent_id'] = $user_value['id'];
                    $parent_user = $this->user_model->getUserList($parent_user_where, 1, 0, 'performance desc');



                    $parent_user_money = $user_value['performance'] - $parent_user[0]['performance'];

                    if ($parent_user_money > $first_money) {
                        $update_date = array();

                        $reward_money = $mouth_money * $user_level_value['reward'];
                        $update_date['money'] = $user_value['money'] + $reward_money;
                        $update_date['user_level'] = $user_level_value['id'];
                        $update_date['balance']   = $user_value['balance'] + $reward_money;

                        $return = $this->user_model->editUser(array('id' => $user_value['id']), $update_date);
                        if ($return) {
                            $add_money_log_data = array();
                            $add_money_log_data[] = array(
                                'user_id' => $user_value['id'],
                                'username' => $user_value['username'],
                                'true_name' => $user_value['true_name'],
                                'money' => $reward_money,
                                'type' => 'welfare',
                                'remark' => $user_value['true_name'] . '，恭喜您提升到' . $user_level_value['user_level_name'] . '奖励您' . $reward_money . '福利',
                                'create_time' =>  time()
                            );


                            $this->add_money_log($add_money_log_data);
                        }
                    }
                }
            }
        }
        return true;
    }
    /**
     * 更新会员级别，团队业绩
     */
    public function updatelevel($user, $mouth_money = '0')
    {

        if ($user['parent_id'] > 0) {
            $this->load->model('user_model');
            $parent_user_where = array('parent_id' => $user['parent_id']);
            $parent_user_child = $this->user_model->getUserList($parent_user_where, 2, 0, 'performance desc');

            $parent_user = $this->user_model->checkUser(array('user.id' => $user['parent_id']));
            if (count($parent_user_child) > 1) {
                /*if(!$mouth_money){
                           $today = date("Y-m-d");
                           $day=$this->getthemonth($today);
                           $firstday=  strtotime($day[0]);
                           $lastday= strtotime($day[1]);
                           $mouth_money_tmp=$this->user_model->where("create_time between ".$firstday ." and ".$lastday )->select('sum(price) as mouth_money')->find();
                           $mouth_money=$mouth_money_tmp['mouth_money'];
                           
                        }*/
                if ($parent_user_child[0]['performance'] > 0) {

                    $other_performance_tmp =  $this->user_model->getFeildList(array('id !=' => $parent_user_child[0]['id'], 'parent_id' => $parent_user['id']), 'sum(performance) as other_performance ');
                    $other_price_tmp =  $this->user_model->getFeildList(array('id !=' => $parent_user_child[0]['id'], 'parent_id' => $parent_user['id']), 'sum(price) as other_price ');

                    $other_performance = $other_performance_tmp[0]['other_performance'];
                    $other_price = $other_price_tmp[0]['other_price'];
                    if ($other_price > 0) {
                        $other_performance = $other_performance + $other_price;
                    }

                    $this->editUserLevels($parent_user, $other_performance, $mouth_money);
                } else {
                    $this->updatelevel2($parent_user, $mouth_money);
                }
            }
            if ($parent_user['parent_id']) {
                $this->updatelevel($parent_user, $mouth_money);
            }
        }
    }
    /**
     * 没有第三级下处理晋升
     */
    public function updatelevel2($parent_user, $mouth_money)
    {
        $this->load->model('user_model');
        $user_first_child = $this->user_model->getUserList(array('parent_id' => $parent_user['id']), '1', 0, 'price desc');
        $count_price = $this->user_model->getFeildList(array('parent_id' => $parent_user['id']), ' sum(price) as count_price');

        $other_performance = $count_price[0]['count_price'] - $user_first_child[0]['price'];
        $this->editUserLevels($parent_user, $other_performance, $mouth_money);
    }
    /**
     * 修改用户等级
     */
    private function editUserLevels($parent_user, $other_performance, $mouth_money)
    {
        $this->load->model('user_level_model');

        $user_level = array();
        $user_level_where = array();
        $user_level_where = array('status' => 1, 'group_performance <=' => $parent_user['performance'], 'other_performance <=' => $other_performance);

        $user_level = $this->user_level_model->getUserLevelList($user_level_where, '1', 0, 'other_performance desc');
        $old_level = $this->user_level_model->checkUserLevel(array('id' => $parent_user['user_level']));
        if ($user_level[0] && $user_level[0]['id'] != $parent_user['user_level'] && $user_level[0]['sort'] > $old_level['sort']) {
            $reward_money = $mouth_money * $user_level[0]['reward'];

            $update_date['money'] = $parent_user['money'] + $reward_money;
            $update_date['user_level'] = $user_level[0]['id'];
            $update_date['balance']   = $parent_user['balance'] + $reward_money;
            $update_date['shengji_time'] = time();

            $return = $this->user_model->editUser(array('id' => $parent_user['id']), $update_date);
            //记录升级日志
            $user_level_log = array();
            $user_level_log['from_level'] = $parent_user['user_level'];
            $user_level_log['to_level'] = $update_date['user_level'];
            $user_level_log['user_id'] = $parent_user['id'];
            $user_level_log['create_time'] = time();
            $this->load->model('user_level_log_model');
            $this->user_level_log_model->addUserLevelLog($user_level_log);

            if ($return && $reward_money > 0) {
                $add_money_log_data = array();
                $add_money_log_data[] = array(
                    'user_id' => $parent_user['id'],
                    'username' => $parent_user['username'],
                    'true_name' => $parent_user['true_name'],
                    'money' => $reward_money,
                    'type' => 'welfare',
                    'remark' => $parent_user['true_name'] . '，恭喜您提升到' . $user_level[0]['user_level_name'] . '奖励您' . $reward_money . '福利',
                    'create_time' =>  time()
                );


                $this->add_money_log($add_money_log_data);
                if ($parent_user['parent_id']) {
                    $this->updatelevel($parent_user, $mouth_money);
                }
            }
        }
    }

    /**
     * 添加会员后处理业绩
     */
    public function getperformance($user, $first = 1)
    {
        if (empty($user['source_user_id'])) {
            $user['source_user_id'] = $user['id'];
        }
        $this->load->model('user_yeji_log_model');

        if ($user['parent_id']) {
            $parent_user = $this->user_model->checkUser(array('user.id' => $user['parent_id']));
            if ($parent_user) {
                $this->load->model('user_model');
                $update = array();
                $update['performance'] = $parent_user['performance'] + $user['price'];
                $update['score'] = $parent_user['score'] + $user['price'];
                $this->user_model->editUser(array('id' => $parent_user['id']), $update);
                //保存用户业绩记录
                $this->user_yeji_log_model->save([
                    'user_id' => $parent_user['id'],
                    'source_user_id' => $user['source_user_id'],
                    'zhitui' => $first == 1 ? $user['price'] : 0,
                    'tuandui' => $first == 0 ? $user['price'] : 0,
                    'create_time' => time(),
                    'day' => date('Y-m-d H'),
                ]);
                if ($parent_user['parent_id'] > 0) {
                    $parent_user['source_user_id'] = $user['source_user_id'];
                    $parent_user['price'] = $user['price'];
                    $this->getperformance($parent_user, 0);
                }
            }
        }
    }
    /**
     * 获取当前月份第一天和最后一天
     */
    function getthemonth($date)
    {
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
        return array($firstday, $lastday);
    }
}
